package tree;

public class MyTree {
    private Node root = new Node();

    public void infixOrder() {
        if (this.root != null) {
            this.root.infixOrder();
        } else {
            System.out.println("二叉树为空");
        }
    }

    public class Node {
        private int n;
        private Node left;
        private Node right;

        public void Node() {
        }

        public void Node(int n) {
            this.n = n;
        }

        public String toString() {
            return "Node{" + "no=" + n + '}';
        }

        //中序遍历
        public void infixOrder() {
            //递归向左子树中序遍历
            if (this.left != null) {
                this.left.infixOrder();
            }
            System.out.println(this);
            //递归向右子树中序排列
            if (this.right != null) {
                this.right.infixOrder();
            }
        }
    }

    public void add(int a) {
        //1.判断是否有根节点
        if (root == null) {
            root = new Node();
            root.n = a;
            return;
        }
        //定义新节点
        Node node = root;
        //新建父节点，保存上节点
        Node dadNode;
        while (true) {
            dadNode = node;
            if (node.n < a) {
                node = node.right;
                if (node == null) {
                    dadNode.right = new Node();
                    dadNode.right.n = a;
                    return;
                }
            }else if (node.n > a) {
                node = node.left;
                if (node == null) {
                    dadNode.left = new Node();
                    dadNode.left.n = a;
                    return;
                }
            }
        }


    }
}
